<template>
  <div v-if="isGain" class="weather-card">
    <div class="weather-item">
      <div v-for="(item, index) in casts">
        <span>{{ timeData(item.week, index) }}</span>
        <span>{{ item.date.slice(-5) }}</span>
        <span>{{ item.dayweather }}</span>
        <span>风力 {{ item.daypower }}级</span>
      </div>
    </div>
    <v-chart :option="option"></v-chart>
  </div>
  <div v-else class="cardLoading">加载中...</div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
const option = ref({});

const isGain = ref(false);

const props = defineProps({
  casts: {
    type: Array,
    required: true,
    default: () => [],
  },
});

const timeData = (value, index) => {
  const week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  if (index === 0) {
    return '今天';
  } else if (index === 1) {
    return '明天';
  } else {
    return week[value - 1];
  }
};

const dataShow = (day, night) => {
  option.value = {
    xAxis: {
      type: 'category',
      show: false,
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    grid: {
      top: 20,
      right: 0,
      bottom: 30,
      left: 0,
    },
    series: [
      {
        type: 'line',
        smooth: true,
        data: day,
        label: {
          show: true,
          position: 'top',
          color: 'white',
          fontSize: 12,
          formatter: function (params) {
            return `白${params.value}℃`;
          },
        },
      },
      {
        type: 'line',
        smooth: true,
        data: night,
        label: {
          show: true,
          position: 'bottom',
          color: 'white',
          fontSize: 12,
          formatter: function (params) {
            return `晚${params.value}℃`;
          },
        },
      },
    ],
  };
};

watch(
  () => props.casts,
  (newCasts) => {
    if (newCasts && newCasts.length > 0) {
      const daytemp = props.casts.map((item) => item.daytemp);
      const nighttemp = props.casts.map((item) => item.nighttemp);
      if(daytemp.length)isGain.value = true;
      dataShow(daytemp, nighttemp);
    }
  },
  { teep: true }
);

onMounted(() => {
  if (props.casts) {
    const daytemp = props.casts.map((item) => item.daytemp);
    const nighttemp = props.casts.map((item) => item.nighttemp);
    if(daytemp.length)isGain.value = true;
    dataShow(daytemp, nighttemp);
  }
});
</script>

<style lang="scss" scoped>
.weather-card {
  margin-top: 8px;
  padding: 40px 48px 0;
  background-color: rgb(0 78 113);
  .weather-item {
    display: flex;
    gap: 24px;
    div {
      display: flex;
      flex-direction: column;
      gap: 16px;
      color: white;
      flex: 1;
      text-align: center;
      line-height: 24px;
    }
  }
  .echarts {
    height: 180px;
    margin-top: 30px;
    z-index: 3;
  }
}
.cardLoading {
  text-align: center;
  color: white;
  margin-top: 8px;
  padding: 40px 48px;
  font-size: 18px;
  background-color: rgb(0 78 113);
}
</style>
